<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="5" :sm="8">
            <a-form-item label="所属区域">
              <j-select-depart placeholder="请选择" v-model="queryParam.areaId" />
            </a-form-item>
          </a-col>
          <a-col :md="5" :sm="8">
            <a-form-item label="村庄名称">
              <a-input placeholder="模糊查询" v-model="villageName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="customerSearchReset" icon="reload" style="margin-left: 8px"
              >重置</a-button
              >
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <!-- 操作按钮区域 -->
    <div class="table-operator" style="display: flex">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('村庄')">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <!-- 高级查询区域 -->
      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
      <a-button type="primary" icon="download" @click="loadImg()">下载二维码</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>

    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="qrCodeImg" slot-scope="qrCodeImg,record" >
          <!--          <span>{{record.terminalName}}</span>-->
          <!--            <a-qrcode value="https://img1.baidu.com/" />-->
          <!--          <qrcode value="https://img1.baidu.com/" :size="200" color="" type="image"></qrcode>-->
          <img :src="qrCodeImg" alt="" height="30px" @click="changeFn(qrCodeImg,record.villageName)"/>
          <a-modal :title="terName"
                   maskClosable
                   :destroyOnClose="false"
                   :visible="visible"  :closable="false"
                   :maskStyle="{background:'rgba(0,0,0,.1)'}"
                   :bodyStyle="{ height: '420px', overflowY: 'auto' }"
                   centered>
            <div style="text-align: center"><img :src="urlImage" alt="" height="84%" width="74%"/></div>
            <div class="print" @click="loadCode()">下载打印</div>
            <template slot="footer">
              <a-button type="primary"  @click="confirmMessage">确认</a-button>
            </template>
          </a-modal>
        </template>
        <template slot="imgSlot" slot-scope="text,record">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>

    <village-modal ref="modalForm" @ok="modalFormOk"></village-modal>
  </a-card>
</template>

<script>
  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import VillageModal from './modules/Village/VillageModal'
  import FileSaver from 'file-saver';
  import { getAction } from '@/api/manage'
  export default {
    name: 'VillageList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      VillageModal
    },
    data () {
      return {
        description: '村庄管理页面',
        villageName:'',
        visible:false,
        urlImage:'',
        terName:'',
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'村庄名称',
            align:"center",
            dataIndex: 'villageName'
          },
          {
            title: '所属区域',
            align: 'center',
            dataIndex: 'areaId_dictText',
          },
          {
            title:'村庄属性',
            align:"center",
            dataIndex: 'attr_dictText'
          },
          {
            title:'排水户',
            align:"center",
            dataIndex: 'farmersNum'
          },
          {
            title:'接入终端',
            align:"center",
            dataIndex: 'terminalNum'
          },
          {
            title:'管网长度',
            align:"center",
            dataIndex: 'pipLength'
          },
          {
            title:'运维企业',
            align:"center",
            dataIndex: 'enterpriseId_dictText'
          },
          {
            title:'运维人员',
            align:"center",
            dataIndex: 'operatorIdsLabel'
          },
          {
            title:'村二维码',
            align:"center",
            dataIndex: 'qr',
            scopedSlots: { customRender: 'qrCodeImg' },
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          list: "/ps/village/list",
          delete: "/ps/village/delete",
          deleteBatch: "/ps/village/deleteBatch",
          exportXlsUrl: "/ps/village/exportXls",
          importExcelUrl: "ps/village/importExcel",
        },
        dictOptions:{},
        superFieldList:[],
      }
    },
    watch: {
      villageName(villageName) {
        if (villageName) {
          this.queryParam.villageName = `*${villageName}*`
        } else {
          this.queryParam.villageName = ''
        }
      },
    },
    created() {
    this.getSuperFieldList();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      confirmMessage(){
        this.visible=false
      },
      customerSearchReset() {
        this.villageName = ''
        this.searchReset()
      },
      changeFn(url,title){
        this.terName=title
        this.urlImage=url
        this.visible=true
      },
      // loadImg(){
      //   console.log(this.superFieldList,'7.23333333333333333')
      // },
     async loadImg() {
        if(this.selectedRowKeys.length==0){
          this.$message.error('请选择村庄!')
          return
        }
        const res = await getAction(`/ps/village/queryByIds`, { ids:this.selectedRowKeys.join(',') })
        if (res.success) {
          var blogTitle = '打包二维码图片';
          var zip = new JSZip();
          var imgs = zip.folder(blogTitle);
          var baseList = [];
          // 要下载图片的url
          var arr = res.result.map((item)=>item.qr);//这里数组内的图片,可以换成自己的图片url地址!
          // 下载后图片的文件名，个数应与arr对应
          var imgNameList =res.result.map((item)=>item.villageName);//这里的数组内的图片名字,可以换成自己对应的!如果是后端返回的,那么
          //就可以从后端返回的数据里面取到图片名字,push到数组内!
          for (var i = 0; i < arr.length; i++) {
            let image = new Image();
            // 解决跨域 Canvas 污染问题
            image.setAttribute('crossOrigin', 'anonymous');

            image.onload = function () {
              let canvas = document.createElement('canvas');
              canvas.width = image.width;
              canvas.height = image.height;

              let context = canvas.getContext('2d');
              context.drawImage(image, 0, 0, image.width, image.height);

              let url = canvas.toDataURL(); // 得到图片的base64编码数据
              canvas.toDataURL('image/png');

              baseList.push(url.substring(22));    // 去掉base64编码前的 data:image/png;base64,
              if (baseList.length === arr.length && baseList.length > 0) {
                for (let k = 0; k < baseList.length; k++) {
                  imgs.file(imgNameList[k] + '.png', baseList[k], {base64: true})
                }
                zip.generateAsync({type: 'blob'}).then(function (content) {
                  // see FileSaver.js
                  FileSaver.saveAs(content, blogTitle + '.zip');
                });
              }

            };
            image.src = arr[i];
          }
        }
      },
      loadCode() {
        let image = new Image();
        let a = document.createElement("a"); // 生成一个a元素
        let event = new MouseEvent("click"); // 创建一个单击事件
        a.download = this.terName || "终端图片"; // 设置图片名称
        a.href = this.urlImage; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
        image.src = this.urlImage;
      },
      initDictConfig(){

      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'villageName',text:'村庄名称',dictCode:''})
        fieldList.push({type:'string',value:'farmersNum',text:'排水户',dictCode:''})
        fieldList.push({type:'Text',value:'aerialPhoto',text:'村庄实景航拍图',dictCode:''})
        fieldList.push({type:'string',value:'operatorIdsLabel',text:'运维人员',dictCode:''})
        fieldList.push({type:'string',value:'enterpriseId_dictText',text:'运维企业',dictCode:''})
        fieldList.push({type:'BigDecimal',value:'longitude',text:'经度',dictCode:''})
        fieldList.push({type:'BigDecimal',value:'latitude',text:'纬度',dictCode:''})
        fieldList.push({type:'int',value:'attr_dictText',text:'村庄属性',dictCode:''})
        fieldList.push({type:'string',value:'areaId',text:'区域id',dictCode:''})
        fieldList.push({type:'string',value:'qr',text:'村二维码',dictCode:''})
        fieldList.push({type:'string',value:'terminalNum',text:'接入终端',dictCode:''})
        fieldList.push({type:'string',value:'pipLength',text:'管网长度',dictCode:''})
        this.superFieldList = fieldList
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
  .print{
    width: 70px;
    height: 28px;
    background-color: #cccccc;
    line-height: 28px;
    text-align: center;
    font-weight: bold;
  }
</style>